package la.bbs558.controller.base;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author: WeiHanmin
 * @description:
 * @time: 2021-07-14 10:20:12
 */
@Data
@Slf4j
public abstract class BaseController {

    @Autowired
    protected HttpServletResponse response;

    @Autowired
    protected HttpServletRequest request;

    /**
     * @Description 获取request中的参数
     *
     * @param
     * @return  java.util.Map<java.lang.String,java.lang.String>
     * @author bbs558
     * @date 2021/7/14 11:34 上午
     */
    public Map<String, String> paramsMap() {
        Map<String, String> result = Maps.newHashMap();
        try {
            Map<String, String[]> parameterMap = request.getParameterMap();
            parameterMap.forEach((key, value) -> {
                if (key != null && value != null && value.length != 0) {
                    result.put(key, value[0]);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取request中的参数失败：{}", e.getMessage());
        }
        return result;
    }

    /**
     * @Description 获取request中的参数并转化为对象
     *
     * @param
     * @return  java.util.Map<java.lang.String,java.lang.String>
     * @author bbs558
     * @date 2021/7/14 11:34 上午
     */
    public <T> T paramsMap(Class<T> tClass) {
        try {
            return JSON.parseObject(JSON.toJSONString(paramsMap()),tClass);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }
}
